package org.farm2.llm.service.impl;

import com.farm2.llm.client.inter.Farm2EmbedClientInter;
import com.farm2.llm.client.inter.Farm2LlmClientInter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.farm2.base.db.FarmDbFields;
import org.farm2.base.domain.FarmUserContextLoader;
import org.farm2.base.exception.FarmAppException;
import org.farm2.base.exception.FarmExceptionUtils;
import org.farm2.base.password.FarmPasswordEncoder;
import org.farm2.llm.dao.LlmClientDao;
import org.farm2.llm.domain.LlmClient;
import org.farm2.llm.enums.LlmClientFuncKeyEnum;
import org.farm2.llm.service.LlmClientServiceInter;
import org.farm2.tools.bean.FarmBeanUtils;
import org.farm2.tools.db.DataQuery;
import org.farm2.tools.db.DataResult;
import org.farm2.tools.db.commons.DBRule;
import org.farm2.tools.db.commons.DBRuleList;
import org.farm2.tools.i18n.I18n;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**大模型接口 
 * @author cbtg自动生成  2025-2-13 22:00:30 
 */
@Service
@Slf4j
public class LlmClientServiceImpl implements LlmClientServiceInter {


    @Autowired
    private LlmClientDao llmClientDao;

    @Transactional
    @Override
    public LlmClient insertLlmClientEntity(LlmClient llmClient) {
        FarmDbFields.initInsertBean(llmClient, FarmUserContextLoader.getCurrentUser());

        if (llmClient.getFunckey().equals(LlmClientFuncKeyEnum.TALK.name())) {
            Farm2LlmClientInter client = null;
            try {
                client = (Farm2LlmClientInter) FarmBeanUtils.getInstance(llmClient.getImplclass());
            } catch (Exception e) {
                throw new RuntimeException("为发现对应接口类：" + llmClient.getImplclass());
            }
            llmClient.setName(client.getName());
        }
        if (llmClient.getFunckey().equals(LlmClientFuncKeyEnum.EMB.name())) {
            Farm2EmbedClientInter client = null;
            try {
                client = (Farm2EmbedClientInter) FarmBeanUtils.getInstance(llmClient.getImplclass());
            } catch (Exception e) {
                throw new RuntimeException("为发现对应接口类：" + llmClient.getImplclass());
            }
            llmClient.setName(client.getName());
        }
        FarmDbFields.initField(llmClient, "state", "0");
        FarmDbFields.initField(llmClient, "baseurl", "");
        FarmDbFields.initField(llmClient, "modelkey", "");
        FarmDbFields.initField(llmClient, "tokensize", "3500");

        llmClientDao.insert(llmClient);


        return llmClient;
    }

    @Transactional
    @Override
    public LlmClient editLlmClientEntity(LlmClient llmClient) {
        LlmClient saveLlmClient = getLlmClientById(llmClient.getId());
        FarmExceptionUtils.throwNullEx(saveLlmClient, I18n.msg("大模型接口不存在:?", llmClient.getId()));
        saveLlmClient.setId(llmClient.getId());
        saveLlmClient.setState(llmClient.getState());
        saveLlmClient.setNote(llmClient.getNote());
        saveLlmClient.setEtime(llmClient.getEtime());
        saveLlmClient.setName(llmClient.getName());
        saveLlmClient.setImplclass(llmClient.getImplclass());
        saveLlmClient.setApikey(llmClient.getApikey());
        saveLlmClient.setBaseurl(llmClient.getBaseurl());
        saveLlmClient.setModelkey(llmClient.getModelkey());
        saveLlmClient.setTokensize(llmClient.getTokensize());
        saveLlmClient.setProxyip(llmClient.getProxyip());
        saveLlmClient.setProxyport(llmClient.getProxyport());
        saveLlmClient.setDimensions(llmClient.getDimensions());
        saveLlmClient.setEnformat(llmClient.getEnformat());
        FarmDbFields.initUpdateBean(saveLlmClient, FarmUserContextLoader.getCurrentUser());
        llmClientDao.update(saveLlmClient);
        return saveLlmClient;
    }

    @Transactional
    @Override
    public LlmClient getLlmClientById(String id) {
        return llmClientDao.findById(id);
    }

    @Override
    public List<LlmClient> getLlmClients(DataQuery query) {
        return llmClientDao.queryData(query.setCount(false)).getData(LlmClient.class);
    }



    @Transactional
    @Override
    public DataResult searchLlmClient(DataQuery query) {
        DataResult result = llmClientDao.queryData(query);
        return result;
    }

    @Override
    public int getLlmClientNum(DataQuery query) {
        return llmClientDao.countData(query);
    }


    @Transactional
    @Override
    public void delLlmClient(String id) {
        /*[tree：树形结构使用]
        if ( llmClientDao.findByParentId(id).size() > 0) {
            throw new RuntimeException("不能删除该节点，请先删除其子节点");
        }
        */
        llmClientDao.deleteById(id);
    }
    
    @Override
    public int getNum(DataQuery query) {
        return  llmClientDao.countData(query);
    }

    @Override
    public Farm2LlmClientInter getTalkClient() {
        List<LlmClient> client = llmClientDao.find(DBRuleList.getInstance().add(new DBRule("STATE", "1", "=")).add(new DBRule("FUNCKEY", LlmClientFuncKeyEnum.TALK.name(), "=")).toList());
        if (client.size() <= 0) {
            return null;
        }

        Class<?> clazz = null;
        try {
            int randomNumber = (int) (Math.random() * client.size());
            Farm2LlmClientInter instance = (Farm2LlmClientInter) FarmBeanUtils.getInstance(client.get(randomNumber).getImplclass());
            instance.init(client.get(randomNumber));
            return instance;
        } catch (Exception e) {
            return null;
        }
    }


    @Override
    public Farm2EmbedClientInter getEmbeddingClient() {
        List<LlmClient> client = llmClientDao.find(DBRuleList.getInstance().add(new DBRule("STATE", "1", "=")).add(new DBRule("FUNCKEY", LlmClientFuncKeyEnum.EMB.name(), "=")).toList());
        if (client.size() <= 0) {
            return null;
        }

        Class<?> clazz = null;
        try {
            int randomNumber = (int) (Math.random() * client.size());
            Farm2EmbedClientInter instance = (Farm2EmbedClientInter) FarmBeanUtils.getInstance(client.get(randomNumber).getImplclass());
            instance.init(client.get(randomNumber));
            return instance;
        } catch (Exception e) {
            return null;
        }
    }
}
